package com.flute.icrawler.app.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.icrawler.config.CrawlConfig;
import com.flute.icrawler.config.CrawlConfigUtil;
import com.flute.tools.data.DataIterator;
import com.flute.tools.data.DataRecord;
import com.flute.tools.data.IEditor;
import com.flute.tools.data.mysql.ConnectionInformation;
import com.flute.tools.data.mysql.NewMysqlHandler;

public class MySqlService {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(MySqlService.class);

	private NewMysqlHandler mysqlHandler = null;

	private static boolean isCreateTable = false;

	private static MySqlService mySqlService = null;

	public MySqlService(ConnectionInformation connectionInformation) {
		// TODO Auto-generated constructor stub
		this.mysqlHandler = new NewMysqlHandler(connectionInformation);
	}

	public static MySqlService getInstance(ConnectionInformation connectionInformation) {

		if (null == mySqlService) {
			mySqlService = new MySqlService(connectionInformation);
		}

		return mySqlService;

	}

	public static synchronized void createDataTable(
			ConnectionInformation connectionInformation, String tableName) {

		if (isCreateTable) {
			return;
		}

		NewMysqlHandler mysqlHandler = new NewMysqlHandler(
				connectionInformation);

		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer
				.append("CREATE TABLE IF NOT EXISTS")
				.append(" `")
				.append(tableName)
				.append("` ")
				.append(
						"( `ID` BIGINT(20) NOT NULL AUTO_INCREMENT,  `URL` VARCHAR(500) NOT NULL, `PATH` VARCHAR(200) DEFAULT NULL, `CHARSET` VARCHAR(200) DEFAULT NULL, `CREATE_TIME` DATETIME DEFAULT NULL, PRIMARY KEY (`ID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;")
				.append(" ");

		LOGGER.info("begin to create table name=" + tableName);
		mysqlHandler.execute(stringBuffer.toString());
		LOGGER.info("success to create table name=" + tableName);

		LOGGER.info("", connectionInformation);

		isCreateTable = true;
	}

	/**
	 * 记录抓取数据的相关信息 包括链接名 存储的网页文件所在路径
	 * 
	 * @param crawlDataRecord
	 */
	public void addDataRecord(String dbTableName, DataRecord dataRecord) {

		// createDataTable(connectionInformation, dbTableName);

		IEditor iEditor = mysqlHandler.editor(dbTableName);
		iEditor.addRecord(dataRecord);

	}

	/**
	 * 获取数据
	 * 
	 * @param sql
	 * @return
	 */
	public DataIterator<DataRecord> getDataRecords(String sql) {
		return mysqlHandler.iterator(sql);
	}

	public static void main(String[] args) {

		CrawlConfig config = CrawlConfigUtil
				.newCrawlConfig("f://Downloads/crawler.xml");

	}
}
